<template>
    <el-form ref="ruleFormRef" style="width: 100%" :model="ruleForm" :rules="rules" label-width="auto" class="demo-ruleForm" :size="formSize" status-icon >
        <el-form-item label="项目名称" prop="title">
            <el-input v-model="ruleForm.title" />
        </el-form-item>
        <el-form-item label="用途" prop="purpose">
            <el-input v-model="ruleForm.purpose" />
        </el-form-item>
        <el-form-item label="使用日期" prop="end_date">
            <el-date-picker v-model="ruleForm.end_date" type="date" value-format="YYYY-MM-DD" placeholder="请选择日期" style="width: 100%;" />
        </el-form-item>
    </el-form>
    <div class="mt20 text-center">
        <el-button type="primary" @click="submitForm(ruleFormRef)" :loading="loading"> 保存 </el-button>
    </div>

</template>
  
<script lang="ts" setup>
import { reactive, ref,watch } from 'vue'
import { ElMessage, type ComponentSize, type FormInstance, type FormRules } from 'element-plus'
import http from '../../../../util/request';
const loading = ref<boolean>(false)
interface RuleForm {
    cert_id: number|string
    title: string
    purpose: string
    created_at: string
    end_date: string
} 
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<RuleForm>({
    cert_id: 0,
    title:'',
    purpose: '',
    created_at: '',
    end_date: '',
})

const props = defineProps<{
    id:number
}>()

watch(props,()=>{
    ruleForm.value.cert_id = props.id
    ruleForm.value.title = ''
    ruleForm.value.purpose = ''
    ruleForm.value.end_date = ''
},{ immediate: true })

const rules = reactive<FormRules<RuleForm>>({
    title: [
        { required: true, message: '请输入项目名称', trigger: 'blur' },
    ],
    purpose: [
        { required: true, message: '请输入用途', trigger: 'blur' },
    ],
    end_date: [
        { required: true, message: '请输入使用日期', trigger: 'blur' },
    ]
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            loading.value = true
            http.put('/cert/down',ruleForm.value).then((response:any)=>{
                loading.value = false
                if(response.data.code != 200){
                    ElMessage.error(response.data.msg);return
                }
                ElMessage.success(response.data.msg);
                onDownSave()  
            })
                      
        } else {
            console.log('error submit!', fields)
        }
    })
}

const onDownSave = () => {
    emit('onDownSave')
}

const emit = defineEmits(['onDownSave'])

</script>
<style scoped>
</style>
